import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk_example/jsonserialize/app/update_info.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:im_flutter_sdk_example/widgets/widgets.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';

import 'global.dart';

/// app 升级
class AppUpdateUtil {
  static AppUpdateUtil _instance = AppUpdateUtil._internal();
  factory AppUpdateUtil() => _instance;

  UpdateInfo _appUpdateInfo;
  // bool _shouldUpdate;

  AppUpdateUtil._internal();

  /// 获取更新信息
  Future run(BuildContext context) async {
    var _result = await G.req.app.appInfo();
    UpdateInfo appInfo = UpdateInfo.fromJson(_result.data);
    _appUpdateInfo = appInfo;
    print("appInfo: $appInfo");
    _runAppUpdate();
  }

  static Future<bool> checkVersion() async {
    var _result = await G.req.app.appInfo();
    UpdateInfo appInfo = UpdateInfo.fromJson(_result.data);
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version != appInfo.data.versionCode;
  }

  /// 检查是否有新版
  Future _runAppUpdate() async {
    // 安装
    if (_appUpdateInfo == null) return;
    PackageInfo appInfo = await PackageInfo.fromPlatform();
    bool shouldUpdate = appInfo.version != _appUpdateInfo.data.versionCode;
    if (shouldUpdate) {
      _appUpdateConformDialog(() {
        if (false) {
          // 去苹果店
          // InstallPlugin.gotoAppStore(_appUpdateInfo['url']);
        } else {
          // apk 下载安装
          toastInfo(msg: "开始下载升级包");
          _downloadAPKAndSetup(_appUpdateInfo.data.url);
        }
      });
    }
  }

  /// 下载文件 & 安装
  Future _downloadAPKAndSetup(String fileUrl) async {
    // 下载
    Directory externalDir = await getExternalStorageDirectory();
    String fullPath = externalDir.path + "/release.apk";

    Dio dio = Dio(BaseOptions(
        responseType: ResponseType.bytes,
        followRedirects: false,
        validateStatus: (status) {
          return status < 500;
        }));
    Response response = await dio.get(
      fileUrl,
    );

    File file = File(fullPath);
    var raf = file.openSync(mode: FileMode.write);
    raf.writeFromSync(response.data);
    await raf.close();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    // 安装
    await InstallPlugin.installApk(fullPath, packageInfo.packageName);
  }

  /// 升级确认对话框
  void _appUpdateConformDialog(VoidCallback onPressed) {
    final forceUpdate = _appUpdateInfo.data.forceUpdate;
    showDialog(
        barrierDismissible: forceUpdate,
        builder: (context) {
          return AlertDialog(
            title: Text('发现新版本 ${_appUpdateInfo.data.versionCode}'),
            content: Text("${_appUpdateInfo.data.content}"),
            actions: <Widget>[
              FlatButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('升级'),
                onPressed: () {
                  onPressed();
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
        context: G.getCurrentContext());
  }
}
